define([
	"UtilDir/util",
	"UtilDir/tool",
	"UtilDir/combotree",
	"UtilDir/dialog",
    "UtilDir/searchBlock",
	"EasyUI","EasyUI-lang",
    "FwDir/util/js/bootstrap-select",
    "ZTree", "css!ZTreeCss"
    ],function(Util,Tool,Combotree,Dialog,SearchBlock,Theme){

    var sysPath =  getServer() + "/static/app/fwsjcj";

    var getDeptController = function () {
        return getServer() + "/platform/org/depts";
    };
    var getExpertController = function () {
        return getServer() + "/fw/expert";
    };
	/**
	 * 页面初始化
	 */
	var init = function(){
        initTree()
        initSearchBlock();
        queryBtnBind();
		createAuditGrid("be1fdfcfef684d448c8929e531b770cf");
        $(window).resize(function(){
            createAuditGrid();
        });
//      initSearchForm();
	};
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            createAuditGrid();
        });
        $("#btnReset").click(function () {
            $("#userName").val("");
            $("#userCode").val("");
        });
	};
    var setting = {
        data: {
            simpleData: {
                enable: true,
                idKey: "deptId", //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId" //节点数据中保存其父节点唯一标识的属性名称
            },
            key: {
                name: "deptName" //zTree 节点数据保存节点名称的属性名称  默认值："name"
            },
            view: {
                dblClickExpand: true
            }

        },
        callback: {
            onClick: function (event, treeId, treeNode, clickFlag) {
                createAuditGrid(treeNode.deptId)
                console.log(treeNode)
            },
            onExpand: function (event, treeId, treeNode) {
                var treeObj = $.fn.zTree.getZTreeObj(treeId);
                var node = treeObj.getNodeByTId(treeNode.tId);
                //没有子节点才去查询
                if (node.children == null || node.children == "undefined") {
                    getDeptTreeChild(node, treeObj);
                }
            }
        }
    };
    function initTree() {
        $.ajax({
            type: "get",
            url: getDeptController() + '/depttreerootnode',
            dataType: "json",
            async: false,
            success: function (data) {
                console.log(data)
                // isParent: 0--false;1--true
                for (var i = 0; i < data.length; i++) {
                    if (data[i].isParent == 1) {
                        data[i].isParent = true;
                    } else {
                        data[i].isParent = false;
                    }
                }
                var zTreeObj = $.fn.zTree.init($("#orgtree"), setting, data);

                var zTree = $.fn.zTree.getZTreeObj("orgtree");
                var nodeList = zTree.getNodes();
                for (i = nodeList.length - 1; i >= 0; i--) {
                    var rootNode = nodeList[i];
                    if (rootNode != null) {
                        currDeptId = rootNode.deptId;
                    }
                    zTreeObj.selectNode(zTreeObj.getNodes()[i], false);
                    if (data[i].isParent) {
                        /* 获取选中树节点 */
                        var nodes = zTreeObj.getSelectedNodes();
                        //展开第一级树
                        zTreeObj.expandNode(nodes[0], true);
                        getDeptTreeChild(nodes[0], zTreeObj);
                    }

                }
            }
        });
    }
    // 获取tree的子节点
    var getDeptTreeChild = function (node, treeObj) {
        $.ajax({
            type: 'get',
            dataType: 'json',
            url: getDeptController() + '/' + node.deptId + "/subdepttreenodes",
            success: function (data) {
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].isParent == 1) {
                            data[i].isParent = true;
                        } else {
                            data[i].isParent = false;
                        }
                    }
                    //添加新节点
                    newNode = treeObj.addNodes(node, data);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                common.HintMsg('warning', '加载子组织机构树失败，请联系系统维护人员');
            }
        });
    }

	var createAuditGrid = function(deptId) {
        $("#auditGrid").datagrid({
            url:getServer() + "/fw/expert/page",
			method:"GET",
            fitColumns: true,
            nowrap: false,
            autoRowHeight: false,
            columns:[[
				{field:'userName',title:'姓名',width:'20%',align:'center'},
				{field:'userCode',title:'专家编号',width:'20%',align:'center'},
                {field:'structureType',title:'业务方向',width:'40%',align:'center',
                    formatter: function (value, rowData, rowIndex) {
                    console.log(value)
                        if(value){
                            var structureType;
                            var structureTypeArr=value.split(",");
                            for(var a=0;a<structureTypeArr.length;a++){
                                if(structureTypeArr[a]==0){
                                    structureTypeArr[a] = "砖混结构、砖木结构";
                                }else if(structureTypeArr[a]==1){
                                    structureTypeArr[a] = "多层钢筋混凝土结构";
                                }else if(structureTypeArr[a]==2){
                                    structureTypeArr[a] = "高层结构";
                                }else if(structureTypeArr[a]==3){
                                    structureTypeArr[a] = "工业厂房结构";
                                }else if(structureTypeArr[a]==4){
                                    structureTypeArr[a] = "空旷结构";
                                }else if(structureTypeArr[a]==5){
                                    structureTypeArr[a] = "土木结构";
                                }else if(structureTypeArr[a]==6){
                                    structureTypeArr[a] = "木结构";
                                }else if(structureTypeArr[a]==7){
                                    structureTypeArr[a] = "石结构";
                                }else if(structureTypeArr[a]==8){
                                    structureTypeArr[a] = "其它";
                                }
                            }
                            structureType = structureTypeArr.join();
                            return structureType;
                        }
                    }
                    },
                {field:'operation',title:'操作',width:'20%',align:'center',
                    formatter: function (value, rowData, rowIndex) {
                        if(rowData.structureType){
                            return '<a onclick="operation(\'' + rowData.userId + '\',2,\'' + rowData.structureType + '\',\''+rowData.dataType+'\')">设定范围</a >';
                        }else{
                            return '<a onclick="operation(\'' + rowData.userId + '\',1)">设定范围</a >';
                        }
                    }
                }
            ]],
            queryParams:{
                userName: $("#userName").val(),
                userCode: $("#userCode").val(),
                deptId:deptId,
            },
            pagination: true,
            pageSize: 10
        });
    };
    window.operation = function (userId,saveOrEdit,structureType,dataType) {
        var selectedDivisions = [];
        var buttons = [];
        buttons.push({
            name: '确定',
            callback: function () {
                var item1 = document.getElementsByName("structureType");
                var data1 = [];
                for(x in item1){
                    if(item1[x].checked)
                        data1.push(item1[x].value);
                }
                var item12 = document.getElementsByName("dataType");
                var data2 = [];
                for(x in item12){
                    if(item12[x].checked)
                        data2.push(item12[x].value);
                }
                var structureType=data1.toString().replace(/,/g,",");
                var dataType=data2.toString().replace(/,/g,",");

                if(selectedDivisions.length==0){
                    Util.alert("请选择数据范围");
                }else{
                    if(data1!=""){
                        if(saveOrEdit=="1"){
                            $.ajax({
                                url: getServer() + "/fw/expert/save",
                                contentType: "application/json",
                                data: JSON.stringify({
                                    userId: userId,
                                    structureType:structureType,
                                    dataType:dataType,
                                    divisions:selectedDivisions
                                }),
                                type: "post",
                                success: function (data) {
                                    Util.alert(data.message);
                                    createAuditGrid();
                                }
                            });
                        }else{
                            $.ajax({
                                url: getServer() + "/fw/expert/edit",
                                contentType: "application/json",
                                data: JSON.stringify({
                                    userId: userId,
                                    structureType:structureType,
                                    dataType:dataType,
                                    divisions:selectedDivisions
                                }),
                                type: "post",
                                success: function (data) {
                                    Util.alert(data.message);
                                    createAuditGrid();
                                }
                            });
                        }
                        dialog.hide();
                    }else{
                        Util.alert("请选择结构类型");
                    }
                }

            }
        });
        var dialog = Dialog({
            id: "viewTeamDialog",
            cache: false,
            title: '请选择', //dialog标题
            width: "600px",
            height: "330px",
            body: '<div id="TeamGrid">' +
                '<div class="col-md-12 form-horizontal">' +
                '<div class="form-group">' +
                '<strong>数据范围</strong>'+
                '</div>' +
                '</div>' +
                '<div class="col-md-12 form-horizontal">' +
                '<div class="form-group">' +
                '<label class="col-md-2 control-label" for="division">行政区划:</label>' +
                '<div class="col-md-10">' +
                '<input type="hidden" class="form-control" id="divisionId" name="divisionId">' +
                '<input class="form-control" id="division" type="text" name="division" class="easyui-combobox">' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="col-md-12 form-horizontal">' +
                '<div class="form-group">' +
                '<strong>结构类型</strong>'+
                '</div>' +
                '</div>' +
                '<div class="col-md-12 form-horizontal">' +
                '<div class="form-group">' +
                '<div class="col-md-4">' +
                ' <label class="checkbox-inline">' +
                ' <input type="checkbox" name="structureType" value="0"> 砖混结构、砖木结构' +
                '</label>' +
                '</div>' +
                '<div class="col-md-4">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="structureType" value="1"> 多层钢筋混凝土结构' +
                '</label>' +
                '</div>' +

                '<div class="col-md-4">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="structureType" value="2"> 高层结构' +
                '</label>' +
                '</div>' +
                '<div class="col-md-4">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="structureType" value="3"> 工业厂房结构' +
                '</label>' +
                '</div>' +

                '<div class="col-md-4">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="structureType" value="4"> 空旷结构' +
                '</label>' +
                '</div>' +
                '<div class="col-md-4">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="structureType" value="5"> 土木结构' +
                '</label>' +
                '</div>' +

                '<div class="col-md-4">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="structureType" value="6"> 木结构' +
                '</label>' +
                '</div>' +
                '<div class="col-md-4">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="structureType" value="7"> 石结构' +
                '</label>' +
                '</div>' +

                '<div class="col-md-4">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="structureType" value="8"> 其它' +
                '</label>' +
                '</div>' +

                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="col-md-12 form-horizontal">' +
                '<div class="form-group">' +
                '<strong>数据类型</strong>'+
                '</div>' +
                '</div>' +
                '<div class="col-md-12 form-horizontal">' +
                '<div class="form-group">' +
                '<div class="col-md-3">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="dataType" value="0" checked disabled> 基本信息' +
                '</label>' +
                '<div style="margin-top: 10px;color: #808180;">(样本编号、建筑物名称，所属省、市、区县)</div>'+
                '</div>' +
                '<div class="col-md-3">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="dataType" value="1" id="info"> 详细信息' +
                '</label>' +
                '<div style="margin-top: 10px;color: #808180;">(经度、纬度、设防标准、自振周期等其他信息)</div>'+
                '</div>' +

                '<div class="col-md-3">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="dataType" value="2"> 附件' +
                '</label>' +
                '<div style="margin-top: 10px;color: #808180;">(图片、文档等附件)</div>'+
                '</div>' +

                '<div class="col-md-3">' +
                '<label class="checkbox-inline">' +
                '<input type="checkbox" name="dataType" value="3" id="allowDownload"> 是否允许下载数据信息' +
                '</label>' +
                '<div style="margin-top: 10px;color: #808180;"></div>'+
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>',
            buttons: buttons,
            afterOpen: function () {
                $('#info').click(function(){
                    if($(this).is(":checked")==true){
                        $('#allowDownload').attr("disabled",false);
                    }else{
                        $('#allowDownload').attr("disabled",true);
                        $('#allowDownload').attr("checked",false);
                    }
                })
                initDivision(userId)
                if(structureType){
                    var checkeds = structureType;
                    //拆分为字符串数组
                    var checkArray =checkeds.split(",");
                    //获得所有的复选框对象
                    var checkBoxAll = $("input[name='structureType']");
                    //获得所有复选框（新闻,微信,论坛，问答，博客，平媒）的value值，然后，用checkArray中的值和他们比较，如果有，则说明该复选框被选中
                    for(var i=0;i<checkArray.length;i++){
                        //获取所有复选框对象的value属性，然后，用checkArray[i]和他们匹配，如果有，则说明他应被选中
                        $.each(checkBoxAll,function(j,checkbox){
                            //获取复选框的value属性
                            var checkValue=$(checkbox).val();
                            if(checkArray[i]==checkValue){
                                $(checkbox).attr("checked",true);
                            }
                        })
                    }
                    var checkeds1 = dataType;
                    //拆分为字符串数组
                    var checkArray1 =checkeds1.split(",");
                    //获得所有的复选框对象
                    var checkBoxAll1 = $("input[name='dataType']");
                    //获得所有复选框（新闻,微信,论坛，问答，博客，平媒）的value值，然后，用checkArray中的值和他们比较，如果有，则说明该复选框被选中
                    for(var i=0;i<checkArray1.length;i++){
                        //获取所有复选框对象的value属性，然后，用checkArray[i]和他们匹配，如果有，则说明他应被选中
                        $.each(checkBoxAll1,function(j,checkbox){
                            //获取复选框的value属性
                            var checkValue1=$(checkbox).val();
                            if(checkArray1[i]==checkValue1){
                                $(checkbox).attr("checked",true);
                            }
                        })
                    }
                }
                if(!$('#info').is(':checked')){
                    $('#allowDownload').attr("disabled",true);
                }
            }
        });
        dialog.show();

        // 初始化行政区划
        var initDivision = function (userId) {
            $.ajax({
                url: getServer() + "/fw/expert/initZtree",
                type: 'GET',
                success: function (res) {
                    // 实例化组合树
                    divisioncombotree = Combotree({
                        // combo组件相关配置
                        combo: {
                            //要渲染的input的id
                            id: "division",
                            //下拉框的类型：单选or多选
                            multi: true,
                            key: {
                                idKey: "divisionId",
                                textKey: "divisionName"
                            },
                            // placeholder: "请选择……",
                            event: {
                                onShowPanel: function () {},
                                onHidePanel: function () {},
                                onChange: function (n, o) {
                                    selectedDivisions = n
//                              if (n[0] && n[0].divisionName == "中华人民共和国") {
////                                  Util.alert("请不要选择中华人民共和国", function () {
////                                      $("#division").val('');
////                                      $("#divisionId").val('');
////                                  })
////                                  divisioncombotree.clear()
////                                  selectedDivisions = []
//                              } else {
//                                  n[0] && $("#divisionId").val(n[0].divisionId);
//                                  n[0] && $("#division").val(n[0].divisionName);
//                              }
                                }
                            }
                        },
                        // ztree组件相关配置
                        ztree: {
                            data: {
                                simpleData: {
                                    enable: true,
                                    idKey: "divisionId", // 主键属性名
                                    pIdKey: "parentId" // 父节点属性名
                                },
                                key: {
                                    name: "divisionName" // 显示名称属性名
                                }
                            },
                            check: {
                                chkboxType: {
                                    'Y': 'ps',
                                    'N': 'ps'
                                }
                            }
                        },
                        data: res,
                        formatter: function (node) {
                            node.open = false;
                        },
                        value: $("#divisionId").val(),
                        search: {
                            enable: true,
                            fields: ["divisionName"]
                        }
                    });
                    $.ajax({
                        url: getExpertController() + "/getDataRange/"+userId,
                        contentType: "application/json",
                        type: "get",
                        success: function (data) {
                            console.log(data)
                            let selectId = [];
                            for(let i = 0;i < data.length;i++){
                                selectId.push(data[i].divisionId)
                            }
                            console.log(selectId)
                            divisioncombotree.setValue(selectId)
                        }
                    });
                }
            });
        }
    };
	return {
		init:init
	};
});
